package com.android.vestel.photoroid;

import java.io.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;


public class FlickrUserId2 {
	private static final String API_KEY = "2f47a8b8f51442d4e57ef734c9b1f2f0";
	private String USERNAME;
	private String USER_ID;
	private static final String METHOD_GETUSERID = "flickr.people.findByUsername";
	private static final String USERID_REQUEST="http://api.flickr.com/services/rest/";
	
	FlickrUserId2(String nameOfUser){
		USERNAME = nameOfUser;
		
	}
	
	private void findUserId() throws HttpException, IOException, SAXException, ParserConfigurationException{
		PostMethod pmethod = new PostMethod(USERID_REQUEST);
		
		pmethod.addParameter("method", METHOD_GETUSERID);
		pmethod.addParameter("api_key", API_KEY);
		pmethod.addParameter("username", USERNAME);
		
		
		HttpClient client = new HttpClient();
		
        int statusCode = client.executeMethod(pmethod);
		
		if (statusCode != HttpStatus.SC_OK) {
        	System.err.println("Method failed: " + pmethod.getStatusLine());
        }
        
		InputStream rstream = null;
        
        rstream = pmethod.getResponseBodyAsStream();
        
        Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstream);
        
        Node userIdResponse = response.getElementsByTagName("user").item(0).getAttributes().getNamedItem("id");
        
        if (userIdResponse != null) {
        	USER_ID = userIdResponse.getTextContent();
        } 
        else {
        	System.out.println("an error occured while getting user id");
        	USER_ID = null;
        }
        
	}
	
	public String getUserId() throws HttpException, IOException, SAXException, ParserConfigurationException{
		findUserId();
		return USER_ID;
	}
	

}


